package cn.jsj.hzu.qm.facecloud.pyAi;

import java.io.File;

public class LACConnecter {
	
	/**
	 * 线程池的尺寸
	 * */
	private static int poolSize;
	
	
	
	/**
	 * 基本工作的目录
	 * */
	private static String basicWorkPathString = FilePropreties.getBasicWorkPath();
	
//	private static OutPutStreamManager outPutStreamManager = new OutPutStreamManager();
	private static LACObject[] lacObjects;
	private static String [] statStrings;
	static {
		poolSize = FilePropreties.getPoolSize();
		
		lacObjects = new LACObject[poolSize];
		statStrings = new String[poolSize];
		File f;
		String pathString;
		for(int i = 0; i < poolSize; i++) {
			pathString = basicWorkPathString+File.separator+i;
			System.out.println(pathString);
			System.out.printf("Init LAC [%d of %d]\n", i, poolSize-1);
			f = new File(pathString);
			if (f.isDirectory() == false) {
				f.mkdirs();
			}
			
			lacObjects[i] = new LACObject(pathString);
			statStrings[i] = LACObject.STATE_FREE;
			
			
		}
		System.out.println("Prepare to start outPut Manager...");
		//outPutStreamManager.start();
	}
	
	/**
	 * 
	 * */
	public LACConnecter() {
	}
	
	/***/
	public LACObject getConnectionLacObject() {
		for (int i = 0; i < poolSize; i++) {
			if (statStrings[i].equals(LACObject.STATE_FREE) == true) {
				statStrings[i] = LACObject.STATE_0;
				return lacObjects[i];
			}
		}
		return null;
	}
	
	public void free(LACObject lacObject) {
		synchronized (statStrings) {
			for(int i = 0; i < poolSize; i++) {
				if (lacObjects[i].getWork_path().equals(lacObject.getWork_path()) == true) {
					
					lacObjects[i].setState(LACObject.STATE_0);
					
					statStrings[i] = LACObject.STATE_FREE;
				}
			}
		}
		
	}
	/**
	 * 获取各个线程的状态
	 * @return [线程0状态,线程1状态,...,线程poolSize-1状态]
	 * */
	public static String  getStateString() {
		synchronized (statStrings) {
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append('[');
			for(int i = 0; i < poolSize; i++) {
				stringBuilder.append(statStrings[i]);
				if(i+1 != poolSize) {
					stringBuilder.append(',');
				}
			}
			stringBuilder.append(']');
			return stringBuilder.toString();
		}
	}
	@Override
	protected void finalize() throws Throwable {
		
	}
	
}
